<?php
/**
 * The MIT License
 *
 * Copyright (c) <year> <copyright holders>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author Damiano Ciarla
 * @package plugin
 * @subpackage log/class/db
 */
class Log_Db_MySql extends Log_Abstract_DbGenUtils implements Log_Interface_Connection
{
	private $_link;
	private $_db;

	private $_tableError;
	private $_tableException;

	public function __construct($host, $username, $password, $dbname)
	{
		$this->_link = mysql_connect($host, $username, $password);

		if(!$this->_link)
			throw new Log_Exception(mysql_error(), Log_Exception::MYSQL_CONNECTION_ERROR);

		$this->_db = mysql_select_db($dbname, $this->_link);

		if(!$this->_db)
			throw new Log_Exception(array($dbname, mysql_error()), Log_Exception::MYSQL_SELECT_DB_ERROR);
	}

	public function checkTable($tableError, $tableException)
	{
		$this->_tableError = $tableError;
		$this->_tableException = $tableException;

		$checkError = false;
		$checkException = false;

		// Recupero tutte le tabelle presenti nel database
		$result = mysql_query("SHOW TABLES", $this->_link);

		while($row = mysql_fetch_row($result))
		{
			// Verifico se la tabella degli errori è già stata creata
			if($row[0] == $tableError)
				$checkError = true;

			// Verifico se la tabella delle eccezioni è già stata creata
			if($row[0] == $tableException)
				$checkException = true;
		}

		// Se la tabella degli errori non è stata creata la creo
		if(!$checkError)
		{
			$sql = "
			CREATE TABLE `" . $tableError . "` (
				`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
				`errno` int(10) unsigned DEFAULT NULL,
				`errtype` text COLLATE utf8_unicode_ci,
				`errstr` text COLLATE utf8_unicode_ci,
				`errfile` text COLLATE utf8_unicode_ci,
				`errline` int(10) unsigned DEFAULT NULL,
				`errcontext` text COLLATE utf8_unicode_ci,
				`client_url` text COLLATE utf8_unicode_ci,
				`client_ip` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
				`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
				PRIMARY KEY (`id`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
			";

			mysql_query($sql, $this->_link);
		}

		// Se la tabella delle eccezioni non è stata creata la creo
		if(!$checkException)
		{
			$sql = "
			CREATE TABLE `" . $tableException . "` (
				`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
				`message` text COLLATE utf8_unicode_ci,
				`previus` text COLLATE utf8_unicode_ci,
				`code` int(10) unsigned DEFAULT NULL,
				`file` text COLLATE utf8_unicode_ci,
				`line` int(10) unsigned DEFAULT NULL,
				`trace` text COLLATE utf8_unicode_ci,
				`trace_as_string` text COLLATE utf8_unicode_ci,
				`client_url` text COLLATE utf8_unicode_ci,
				`client_ip` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
				`date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
				PRIMARY KEY (`id`)
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
			";

			mysql_query($sql, $this->_link);
		}
	}

	/**
	 * Metodo che memorizza l'errore che viene intercettato
	 *
	 * @param int $errno Numero identificativo della tipologia dell'errore
	 * @param string $errstr Descrizione
	 * @param string $errfile File dove si è verificato l'errore
	 * @param int $errline Line dove si è verificato l'errore
	 * @param string $errcontext Valori aggiuntivi
	 */
	public function storeError($errno = null, $errstr = null, $errfile = null, $errline = null, $errcontext = null)
	{
		$errtype = $this->_error2string($errno);

		Bxd::includeLib()->httpUtils();
		$client_url = bxd\lib\http\Utils::realUrl();
		$client_ip = bxd\lib\http\Utils::realIp();

		$sql = "
		INSERT INTO `" . $this->_tableError . "` SET
		`errno` = " . (($errno == null) ? "NULL" : "'" . mysql_real_escape_string($errno, $this->_link) . "'") . ",
		`errtype` = " . (($errtype == null) ? "NULL" : "'" . mysql_real_escape_string($errtype, $this->_link) . "'") . ",
		`errstr` = " . (($errstr == null) ? "NULL" : "'" . mysql_real_escape_string($errstr, $this->_link) . "'") . ",
		`errfile` = " . (($errfile == null) ? "NULL" : "'" . mysql_real_escape_string($errfile, $this->_link) . "'") . ",
		`errline` = " . (($errline == null) ? "NULL" : "'" . mysql_real_escape_string($errline, $this->_link) . "'") . ",
		`errcontext` = " . (($errcontext == null) ? "NULL" : "'" . mysql_real_escape_string(print_r($errcontext, true), $this->_link) . "'") . ",
		`client_url` = " . (($client_url == null) ? "NULL" : "'" . mysql_real_escape_string($client_url, $this->_link) . "'") . ",
		`client_ip` = " . (($client_ip == null) ? "NULL" : "'" . mysql_real_escape_string($client_ip, $this->_link) . "'");

		mysql_query($sql, $this->_link);
	}

	/**
	 * Meotodo che memorizza l'eccezione catturata
	 *
	 * @param Exception $e Istanza della classe Exception
	 */
	public function storeException(Exception $e)
	{
		Bxd::includeLib()->httpUtils();
		$client_url = bxd\lib\http\Utils::realUrl();
		$client_ip = bxd\lib\http\Utils::realIp();

		$sql = "
		INSERT INTO `" . $this->_tableException . "` SET
		`message` = " . (($e->getMessage() == null) ? "NULL" : "'" . mysql_real_escape_string($e->getMessage(), $this->_link) . "'") . ",
		`previus` = " . (($e->getPrevious() == null) ? "NULL" : "'" . mysql_real_escape_string($e->getPrevious(), $this->_link) . "'") . ",
		`code` = " . (($e->getCode() == null) ? "NULL" : "'" . mysql_real_escape_string($e->getCode(), $this->_link) . "'") . ",
		`file` = " . (($e->getFile() == null) ? "NULL" : "'" . mysql_real_escape_string($e->getFile(), $this->_link) . "'") . ",
		`line` = " . (($e->getLine() == null) ? "NULL" : "'" . mysql_real_escape_string($e->getLine(), $this->_link) . "'") . ",
		`trace` = " . (($e->getTrace() == null) ? "NULL" : "'" . mysql_real_escape_string(print_r($e->getTrace(), true), $this->_link) . "'") . ",
		`trace_as_string` = " . (($e->getTraceAsString() == null) ? "NULL" : "'" . mysql_real_escape_string($e->getTraceAsString(), $this->_link) . "'") . ",
		`client_url` = " . (($client_url == null) ? "NULL" : "'" . mysql_real_escape_string($client_url, $this->_link) . "'") . ",
		`client_ip` = " . (($client_ip == null) ? "NULL" : "'" . mysql_real_escape_string($client_ip, $this->_link) . "'");

		mysql_query($sql, $this->_link);
	}

	public function countError($type = null)
	{
		$sql = "
		SELECT COUNT(*) tot_result
		FROM `" . $this->_tableError . "`
		WHERE 1
		" . (($type !== null) ? "AND `errtype` = '" . mysql_real_escape_string($type) . "'" : "");

		$result = mysql_query($sql, $this->_link);

		$data = mysql_fetch_assoc($result);
		return $data['tot_result'];
	}

	public function getError($page = 1, $limit = 30, $type = null)
	{
		$sql = "
		SELECT *
		FROM `" . $this->_tableError . "`
		WHERE 1
		" . (($type !== null) ? "AND `errtype` = '" . mysql_real_escape_string($type) . "'" : "") . "
		ORDER BY id DESC
		LIMIT " . (($page - 1) * $limit) . ", " . $limit;

		$result = mysql_query($sql, $this->_link);

		$data = array();

		while($row = mysql_fetch_assoc($result))
			$data[] = $row;

		return $data;
	}

	public function getUniqueTypeError()
	{
		$sql = "
		SELECT `errtype`
		FROM `" . $this->_tableError . "`
		GROUP BY `errtype`
		";

		$result = mysql_query($sql, $this->_link);

		$data = array();

		while($row = mysql_fetch_assoc($result))
			$data[] = $row;

		return $data;
	}

	public function countException()
	{
		$sql = "
		SELECT COUNT(*) tot_result
		FROM `" . $this->_tableException . "`
		";

		$result = mysql_query($sql, $this->_link);

		$data = mysql_fetch_assoc($result);
		return $data['tot_result'];
	}

	public function getException($page = 1, $limit = 30)
	{
		$sql = "
		SELECT *
		FROM `" . $this->_tableException . "`
		ORDER BY id DESC
		LIMIT " . (($page - 1) * $limit) . ", " . $limit;

		$result = mysql_query($sql, $this->_link);

		$data = array();

		while($row = mysql_fetch_assoc($result))
			$data[] = $row;

		return $data;
	}

	public function closeConnection()
	{
		mysql_close($this->_link);
	}
}
?>
